<template>
  <el-container>
    <el-dialog
      :title="isAdd ? '菜单添加' : '菜单编辑'"
      :visible.sync="centerDialogVisible"
      @closed="closeDialog()"
      width="70%"
      height="60%"
      :close-on-click-modal="false"
      center
    >
      <el-form
        ref="menuForm"
        :model="menuForm"
        label-width="150px"
        fullscreenLoading
        :rules="menuFormRules"
      >
        <el-row>
          <el-col :span="8">
            <el-form-item label="菜单编号">
              <el-input
                v-model.trim="menuForm.id"
                disabled
              ></el-input> </el-form-item
          ></el-col>
          <el-col :span="8">
            <el-form-item label="父级菜单编号">
              <el-input
                v-model.trim="menuForm.parentId"
                disabled
              ></el-input> </el-form-item
          ></el-col>
          <el-col :span="8">
            <el-form-item label="菜单标题" prop="title">
              <el-input
                v-model="menuForm.title"
                placeholder="title"
              ></el-input> </el-form-item
          ></el-col>
          <el-col :span="8">
            <el-form-item label="path" prop="path">
              <el-input
                v-model="menuForm.path"
                placeholder="path"
              ></el-input> </el-form-item
          ></el-col>
          <el-col :span="8">
            <el-form-item label="name">
              <el-input
                v-model="menuForm.name"
                placeholder="name"
              ></el-input> </el-form-item
          ></el-col>
          <el-col :span="8">
            <el-form-item label="component" prop="component">
              <el-input
                v-model="menuForm.component"
                placeholder="component"
              ></el-input> </el-form-item
          ></el-col>
          <el-col :span="8">
            <el-form-item label="icon" prop="icon">
              <el-input
                v-model="menuForm.icon"
                placeholder="请输入路由里meta里的图标title"
              ></el-input> </el-form-item
          ></el-col>
          <el-col :span="8">
            <el-form-item label="是否有子节点" prop="hasChildrenNode">
              <el-radio-group v-model="menuForm.hasChildrenNode">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </el-form-item></el-col
          >
          <el-col :span="8">
            <el-form-item
              label="是否始终显示"
              v-show="menuForm.hasChildrenNode"
              prop="alwaysShow"
            >
              <el-radio-group v-model="menuForm.alwaysShow">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </el-form-item></el-col
          >
          <el-col :span="8">
            <el-form-item label="是否隐藏该菜单" prop="hasHidden">
              <el-radio-group v-model="menuForm.hasHidden">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </el-form-item></el-col
          >
          <el-col :span="8">
            <el-form-item label="是否有props参数" prop="hasProps">
              <el-radio-group v-model="menuForm.hasProps">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </el-form-item></el-col
          >
          <el-col :span="8">
            <el-form-item label="是否有独享路由" prop="hasBeforeenter">
              <el-radio-group v-model="menuForm.hasBeforeenter">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </el-form-item></el-col
          >
          <el-col :span="8">
            <el-form-item label="重定向" v-show="!menuForm.parentId">
              <el-input
                v-model="menuForm.redirect"
                placeholder="redirect"
              ></el-input> </el-form-item
          ></el-col>
          <el-col :span="24">
            <div style="text-align: center">
              <el-form-item>
                <el-button
                  type="primary"
                  @click="submitForm('menuForm')"
                  v-loading.fullscreen.lock="fullscreenLoading"
                  >确认</el-button
                >
                <el-button @click="resetForm('menuForm')">重置</el-button>
              </el-form-item>
            </div>
          </el-col>
        </el-row>
      </el-form>
    </el-dialog>
    <el-container>
      <el-main>
        <el-row class="function-button">
          <el-button type="primary" size="small" round @click="handleAdd()"
            >新增根菜单</el-button
          >
          <el-button type="success" size="small" round @click="refresh()"
            >刷新按钮</el-button
          >
          <el-input
            style="width: 20%; margin-left: 40px"
            placeholder="输入菜单标题"
            size="samll"
            prefix-icon="el-icon-search"
            v-model="menuName"
          >
          </el-input>
          <el-button round style="margin-left: 10px" @click="queryByCondition"
            >查询</el-button
          >
        </el-row>
        <template>
          <el-table
            ref="menuTable"
            :header-cell-style="{ 'text-align': 'center' }"
            :cell-style="{ 'text-align': 'center' }"
            v-loading="loading"
            :data="menus"
            fit
            @row-dblclick="handleRowDblclick"
            border
            @cell-click="handleCellClick"
            max-height="700"
            size="medium "
            highlight-current-row
            row-key="id"
            tooltip-effect="dark"
            :tree-props="{
              children: 'children',
              hasChildrenNode: 'hasChildrenNode',
            }"
          >
            <el-table-column prop="id" label="菜单编号" width="100">
            </el-table-column>
            <el-table-column prop="icon" label="菜单图标" width="100">
              <template slot-scope="scope">
                <Item :icon="scope.row.icon"></Item>
              </template>
            </el-table-column>
            <el-table-column prop="title" label="菜单标题" width="150">
              <template slot-scope="scope">
                <span
                  :class="scope.row.hasHidden !== 1 ? 'title' : ''"
                  style=""
                  >{{ scope.row.title }}</span
                >
              </template>
            </el-table-column>
            <el-table-column prop="path" label="菜单路径" width="100">
            </el-table-column>
            <el-table-column prop="name" label="菜单名称" width="100">
            </el-table-column>
            <el-table-column prop="component" label="菜单组件" width="300">
            </el-table-column>
            <el-table-column prop="alwaysShow" label="始终显示">
              <template slot-scope="scope">
                {{ scope.row.alwaysShow == 1 ? '是' : '否' }}
              </template>
            </el-table-column>
            <el-table-column prop="hasHidden" label="是否隐藏"
              ><template slot-scope="scope"
                ><span>{{ scope.row.hasHidden == 1 ? '是' : '否' }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="hasProps" label="是否有props参数" width="150"
              ><template slot-scope="scope"
                ><span>{{ scope.row.hasProps == 1 ? '是' : '否' }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="hasBeforeenter"
              label="是否有独享路由"
              width="150"
              ><template slot-scope="scope"
                ><span>{{ scope.row.hasBeforeenter == 1 ? '是' : '否' }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="hasChildrenNode"
              label="是否有子节点"
              width="150"
              ><template slot-scope="scope"
                ><span>{{ scope.row.hasChildrenNode == 1 ? '是' : '否' }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="redirect" label="重定向" width="150">
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="250">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  @click.stop="handEdit(scope.row)"
                  size="small"
                  >添加子菜单</el-button
                >
                <el-button
                  type="danger"
                  @click.stop="handDel(scope.row)"
                  size="small"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </template>

        <div class="block">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page.sync="currentPage"
            :page-size="pageSize"
            layout="prev, pager, next, jumper"
            :total="total"
          >
          </el-pagination>
        </div>
      </el-main>
    </el-container>
  </el-container>
</template>

<script>
import throttle from 'lodash/throttle'; //
import { mapGetters } from 'vuex';
import { Message } from 'element-ui';
export default {
  name: 'MenuMng',
  data() {
    var validateTitleIsRepeat = async (rule, value, callback) => {
      if (!value) {
        return callback([new Error('标题不能为空')]);
      }
      // 发送请求，判断菜单标题是否重复
      let result = await this.$store.dispatch(
        'MenuMng/checkIsRepeatForMenuTitle',
        value
      );
      if (result.data.flag) {
        if (!this.isAdd) {
          return callback();
        }
      }
      return !result.data.flag
        ? callback()
        : callback([new Error(result.message)]);
    };
    return {
      search: '', // 前端模糊查询
      isAdd: false, // 模态窗口状态标识
      loading: false,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      centerDialogVisible: false, // 模态窗口启用开关
      fullscreenLoading: false,
      menuForm: {}, // 菜单类别添加/修改表单
      menus: [],
      menuName: '', // 查询条件
      menuPid: undefined, // 查询条件  // 默认值 计算机开发/应用类
      categoryList: [],
      menuFormRules: {
        title: [
          {
            required: true,
            validator: validateTitleIsRepeat,
            trigger: 'blur',
          },
        ],
        path: [
          {
            required: true,
            message: '菜单路径（路由里的Path)不能为空',
            trigger: 'blur',
          },
        ],
        component: [
          {
            required: true,
            message: '路由组件不能为空',
            trigger: 'blur',
          },
        ],
        icon: [
          {
            required: true,
            message: '路由图标不能为空',
            trigger: 'blur',
          },
        ],
        hasHidden: [
          {
            required: true,
            message: '',
            trigger: 'change',
          },
        ],
        hasProps: [
          {
            required: true,
            message: '未选择该菜单是否有路由参数',
            trigger: 'change',
          },
        ],
        hasBeforeenter: [
          {
            required: true,
            message: '未选择该路由是否有独享路由',
            trigger: 'change',
          },
        ],
        hasChildrenNode: [
          {
            required: true,
            message: '未选择该菜单是否有子菜单',
            trigger: 'change',
          },
        ],
      },
    };
  },
  computed: {
    // 工作分类
    ...mapGetters('MenuMng', ['menuIPage', 'menuList', 'maxNewId', 'menuTree']),
  },
  watch: {
    menuTree() {
      this.$set(this, 'menus', this.menuTree);
      this.loading = false;
    },
    menuIPage() {
      if (this.menuIPage.currentPage) {
        this.currentPage = this.menuIPage.currentPage;
      }
      if (this.menuIPage.pageSize) {
        this.pageSize = this.menuIPage.pageSize;
      }
      if (this.menuIPage.total) {
        this.total = this.menuIPage.total;
      }
    },
  },
  mounted() {
    this.getMenuTree();
  },
  methods: {
    // 单击表格的某个单元格
    handleCellClick(row, column, cell, event) {
      if (column.label === '菜单标题') {
        if (row.hasHidden !== 1) {
          // 路由跳转
          this.$router.push({
            name: row.name,
          });
        }
      }
    },
    // 双击表格的行事件, 编辑
    async handleRowDblclick(row, column, event) {
      if (this.$refs.menuForm) {
        this.resetForm('menuForm');
      }
      this.menuForm = row;
      this.centerDialogVisible = true;
    },
    // 每页显示多少条
    handleSizeChange(val) {
      this.pageSize = val;
      this.getMenuTree();
    },
    // 当前页
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getMenuTree();
    },

    // 查询菜单类别信息
    getMenuTree() {
      this.$store.dispatch('MenuMng/getMenuTree');
    },
    // 删除菜单类别
    handDel(row) {
      let result;
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true,
      })
        .then(async () => {
          result = await this.$store.dispatch('MenuMng/delMenu', [row.id]);
          this.$message({
            message: result.message,
            type: 'success',
            duration: 2 * 1000,
          });
          this.getMenuTree();
        })
        .catch(() => {
          this.$message({
            message: '取消删除',
            type: 'info',
            duration: 2 * 1000,
          });
        });
    },
    // 刷新菜单列表
    refresh: throttle(async function () {
      this.loading = true;
      this.currentPage = 1;
      await this.getMenuTree();
      // 更新路由
      this.$store.dispatch('GenerateRoutes').then((accessRoutes) => {
        // 根据roles权限生成可访问的路由表
        router.addRoutes(accessRoutes); // 动态添加可访问路由表
      });
      this.$message({
        message: '刷新成功',
        type: 'success',
        duration: 1 * 1000,
      });
    }, 800),

    // 返回当前菜单的子菜单的最大可用编号
    async getChildrenMenuMaxId(parentId) {
      if (!parentId) {
        parentId = 0;
      }
      let result = await this.$store.dispatch(
        'MenuMng/getChildrenMenuMaxId',
        parentId
      );
      return result;
    },

    // 新增菜单类别
    async handleAdd() {
      this.menuForm = {};
      if (this.$refs.menuForm) {
        this.resetForm('menuForm');
      }
      // 返回当前菜单的子菜单的最大可用编号
      let maxNewId = await this.getChildrenMenuMaxId();
      // 自动生成菜单id
      this.$set(this.menuForm, 'id', maxNewId);
      this.isAdd = true;
      this.centerDialogVisible = true;
    },
    // 编辑菜单类别
    async handEdit(row) {
      this.menuForm = {};
      if (this.$refs.menuForm) {
        this.resetForm('menuForm');
      }
      // 获取子项对应的编号
      let maxId = await this.getChildrenMenuMaxId(row.id);
      let parentId = row.id;
      this.$set(this.menuForm, 'parentId', parentId);
      this.$set(this.menuForm, 'id', maxId);

      this.isAdd = true;
      this.centerDialogVisible = true;
    },
    // 重置表单判定状态
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    // 对话框关闭前的回调
    closeDialog() {
      this.isAdd = false;
    },

    // 条件查询
    async queryByCondition() {
      let menuName = this.menuName;
      this.menus = this.filterMenu(this.menuTree, menuName);
    },

    // 条件过滤--递归
    filterMenu(menuData, filterText) {
      // 如果过滤条件为空，返回原数据
      if (!filterText) {
        return menuData;
      }
      const result = [];
      // 遍历菜单树
      menuData.forEach((menu) => {
        // 先判断当前菜单是否匹配
        if (menu.title.includes(filterText)) {
          result.push(menu);
          return;
        }
        // 如果当前菜单不匹配，则递归遍历子菜单
        const children = this.filterMenu(menu.children || [], filterText);
        if (children.length > 0) {
          result.push({
            ...menu,
            children,
          });
        }
      });

      return result;
    },

    // 表单提交
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          this.fullscreenLoading = true;
          try {
            // 接收返回的结果
            let result = {};
            if (this.isAdd) {
              let paramsArray = [];
              let params = {
                ...this.menuForm,
              };
              paramsArray.push(params);
              // 发送请求
              result = await this.$store.dispatch(
                'MenuMng/batchAddMenu',
                paramsArray
              );
            } else {
              result = await this.$store.dispatch(
                'MenuMng/editMenu',
                this.menuForm
              );
            }
            // 执行成功返回结果，
            // 更新专业列表
            this.getMenuTree();
            this.$message({
              message: result.message,
              type: 'success',
              duration: 2 * 1000,
            });
          } catch (error) {
            Message.error(error || 'Has Error');
          } finally {
            // 更新路由
            this.$store.dispatch('GenerateRoutes').then((accessRoutes) => {
              // 根据roles权限生成可访问的路由表
              router.addRoutes(accessRoutes); // 动态添加可访问路由表
            });
            this.fullscreenLoading = false; // 关闭遮罩层
            this.isAdd = false; // 重置表单状态
            this.centerDialogVisible = false; // 关闭模态窗口
          }
        } else {
          return false;
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
// 分页插件居中对齐
.block {
  text-align: center;
}

// 菜单标题样式
.title:hover {
  text-decoration-line: underline;
  color: cornflowerblue;
  cursor: pointer;
}
</style>
